package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.pojo.CardInfo;
import org.example.pojo.Deposit;
import org.example.pojo.UserInfo;
import org.example.service.CardInfoService;
import org.example.service.DepositService;
import org.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/admin/card")
public class CardInfoController {

    @Autowired
    private CardInfoService cardInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private DepositService depositService;

    @GetMapping("/list")
    public ModelAndView list(
            @RequestParam(required = false) String cardId,
            @RequestParam(required = false) String customerName,
            Model model
    ) {
        QueryWrapper<CardInfo> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(cardId)) {
            wrapper.like("card_id", cardId);
        }

        if (StringUtils.hasText(customerName)) {
            // 假设你已经设置好和 UserInfo 的关联查询，可以写成联表条件
            wrapper.inSql("customer_id", "SELECT customer_id FROM user_info WHERE name LIKE '%" + customerName + "%'");
        }

        List<CardInfo> cardList = cardInfoService.list(wrapper);
       
        for (CardInfo cardInfo : cardList) {
            QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("role", "CUSTOMER");
            wrapper1.eq("customer_id",cardInfo.getCustomerId() );
            UserInfo user = userInfoService.getOne(wrapper1);
            String name = user.getName();
            cardInfo.setCustomerName(name);
        }
        
        model.addAttribute("cardList", cardList);
        model.addAttribute("cardId", cardId);
        model.addAttribute("customerName", customerName);

        return new ModelAndView("/admin/card/list");
    }

    // 新增页面
    @GetMapping("/add")
    public String addPage(Model model) {

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("role", "CUSTOMER");


        // 示例：假设营业厅编号是 12345678
        String hallCode = "11223344";
        String randomSuffix = String.format("%08d", new Random().nextInt(100000000));
        String generatedCardId = hallCode + randomSuffix;


        model.addAttribute("generatedCardId", generatedCardId);

        List<Deposit> deposits = depositService.list(new QueryWrapper<>());

        List<UserInfo> userList = userInfoService.list(wrapper);
        model.addAttribute("userList", userList);
        model.addAttribute("savingList", deposits);
        return "admin/card/add";
    }

    // 添加银行卡
    @PostMapping("/save")
    public String addCard(CardInfo cardInfo) {
        cardInfo.setOpenDate(LocalDate.now());
        cardInfoService.save(cardInfo);
        return "redirect:/admin/card/list";
    }

    // 编辑页面
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        CardInfo card = cardInfoService.getById(id);
        model.addAttribute("card", card);
//        model.addAttribute("dateopen",)

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String openDateStr = card.getOpenDate() != null ? card.getOpenDate().format(formatter) : "";
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("role", "CUSTOMER");
        List<UserInfo> userList = userInfoService.list(wrapper);
        model.addAttribute("userList", userList);

        model.addAttribute("openDateStr", openDateStr);

        List<Deposit> deposits = depositService.list(new QueryWrapper<>());

        model.addAttribute("depositTypes", deposits);

        return "admin/card/edit";
    }

    // 修改
    @PostMapping("/update")
    public String updateCard(CardInfo cardInfo) {
        cardInfoService.updateById(cardInfo);
        return "redirect:/admin/card/list";
    }

    // 删除
    @GetMapping("/delete/{id}")
    public String deleteCard(@PathVariable Long id) {
        cardInfoService.removeById(id);
        return "redirect:/admin/card/list";
    }

    // 导出 CSV
    @GetMapping("/export")
    public void exportToCsv(HttpServletResponse response) throws IOException {
        List<CardInfo> list = cardInfoService.list();
        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=card_info.csv");

        PrintWriter writer = response.getWriter();
        writer.println("卡号,币种,开卡日期,开户金额,余额,挂失状态,客户编号,存款类型");

        for (CardInfo c : list) {
            writer.println(String.join(",",
                    c.getCardId().toString(),
                    c.getCurId(),
                    c.getOpenDate().toString(),
                    c.getOpenMoney().toString(),
                    c.getBalance().toString(),
                    c.getIsReportLoss() == 1 ? "挂失" : "正常",
                    c.getCustomerId().toString(),
                    c.getSavingId().toString()
            ));
        }

        writer.flush();
        writer.close();
    }


    @PostMapping("/changePassword")
    public String changePassword(@RequestParam String cardId,
                                 @RequestParam String oldPass,
                                 @RequestParam String newPass,
                                 Model model) {
        CardInfo card = cardInfoService.getById(cardId);
        if (card == null) {
            model.addAttribute("error", "卡号不存在！");
            return "customer/password/form";
        }

        if (!oldPass.equals(card.getPass())) {
            model.addAttribute("error", "原密码不正确！");
            return "customer/password/form";
        }

        card.setPass(newPass); // 如果需要加密，可在此加密
        cardInfoService.updateById(card);

        model.addAttribute("message", "密码修改成功！");
        return "customer/password/form";
    }
}